package jvm;

/**
 * synchronized解决原子性
 *
 * @author: cuihao
 * @create: 2020-06-26 23:29
 **/
public class Atomicity {

    //1.定义全局变量number
    private static int number = 0;
    //新增一个静态变量object
    private static Object object = new Object();

    public static void main(String[] args) throws Exception {
        Runnable runnable = () -> {
            for (int i = 0; i < 10000; i++) {
                //将number++的操作用object对象锁住
                synchronized (object) {
                    number++;
                }
            }
        };
        //2.t1让其自增10000
        Thread t1 = new Thread(runnable);
        t1.start();

        //3.t2让其自增10000
        Thread t2 = new Thread(runnable);
        t2.start();

        //4.等待t1,t2运行结束
        t1.join();
        t2.join();
        System.out.println("number=" + number);
    }


}
